/**
 * jims
 */
package com.jims.master.modules.doctor.web;

import com.jims.master.common.config.Global;
import com.jims.master.common.data.StringData;
import com.jims.master.common.persistence.BaseEntity;
import com.jims.master.common.persistence.Page;
import com.jims.master.common.utils.DateUtils;
import com.jims.master.common.utils.NumberUtils;
import com.jims.master.common.utils.StringUtils;
import com.jims.master.common.web.BaseController;
import com.jims.master.common.web.impl.BaseDto;
import com.jims.master.modules.doctor.entity.PrescriptionApply;
import com.jims.master.modules.doctor.service.ClinicMasterService;
import com.jims.master.modules.doctor.service.PrescriptionApplyService;
import com.jims.master.modules.doctor.service.PrescriptionItemService;
import com.jims.master.modules.operation.entity.OperationCost;
import com.jims.master.modules.operation.service.OperationCostService;
import com.jims.master.modules.sys.utils.UserUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 门诊处方主表Controller
 *
 * @author CTQ
 * @version 2017-03-13
 */
@Controller
@RequestMapping(value = "${adminPath}/doctor/prescriptionApply")
public class PrescriptionApplyController extends BaseController {

    @Autowired
    private PrescriptionApplyService prescriptionApplyService;
    @Autowired
    private PrescriptionItemService prescriptionItemService;
    @Autowired
    private ClinicMasterService clinicMasterService;
    @Autowired
    private OperationCostService operationCostService;
    @ModelAttribute
    public PrescriptionApply get(@RequestParam(required = false) String id) {
        PrescriptionApply entity = null;
        if (StringUtils.isNotBlank(id)) {
            entity = prescriptionApplyService.get(id);
        }
        if (entity == null) {
            entity = new PrescriptionApply();
        }
        return entity;
    }

    @RequiresPermissions("user")
    @RequestMapping(value = {"index", ""})
    public String list(PrescriptionApply prescriptionApply, HttpServletRequest request, HttpServletResponse response, Model model) {
        model.addAttribute("prescriptionApply", prescriptionApply);
        UserUtils userUtils = new UserUtils();
        model.addAttribute("creator",userUtils.getUser().getId());
        model.addAttribute("billingDept",userUtils.getUser().getOrgDept().getId());
        if("".equals(prescriptionApply.getClinicId())|| prescriptionApply.getClinicId() ==null){
            return "modules/doctor/prescription/in/prescriptionIndex";
        } else {
            return "modules/doctor/prescription/prescriptionIndex";
        }
    }

    /**
     * @param prescriptionApply 传递参数
     * @return String    返回类型
     * @throws
     * @Title: applyIndex
     * @Desciption: (加载处方主表列表)
     * @author CTQ
     * @date 2017-03-14
     */
    @RequiresPermissions("user")
    @RequestMapping(value = {"applyIndex", ""})
    public String applyIndex(PrescriptionApply prescriptionApply, Model model) {
        List<PrescriptionApply> list = prescriptionApplyService.findAllList(prescriptionApply);
        model.addAttribute("list", list);
        model.addAttribute("prescriptionApply", prescriptionApply);
        if(!"".equals(prescriptionApply.getClinicId()) && prescriptionApply.getClinicId() != null){
            return "modules/doctor/prescription/prescriptionApplyIndex";
        } else if(!"".equals(prescriptionApply.getVisitId()) && prescriptionApply.getVisitId() != null){
            return "modules/doctor/prescription/in/prescriptionApplyIndex";
        }
        return "";
    }

    @RequiresPermissions("user")
    @RequestMapping(value = "form")
    public String form(PrescriptionApply prescriptionApply, Model model) {
        model.addAttribute("prescriptionApply", prescriptionApply);
        return "modules/doctor/prescription/prescriptionApplyForm";
    }

    @RequiresPermissions("user")
    @RequestMapping(value = "save")
    @ResponseBody
    public StringData save(PrescriptionApply prescriptionApply) {
        StringData data = new StringData();
        String applyId = prescriptionApply.getId();
        PrescriptionApply oldApply = prescriptionApplyService.get(applyId);
        if (oldApply != null && Global.NO.equals(oldApply.getPrescStatus())) {
            data.setCode("error");
            data.setData("请保存此处方后，再新开处方");
            return data;
        }
        if(prescriptionApply.getClinicId() != null){  // 门诊
            prescriptionApply.setBillingDept(clinicMasterService.get(prescriptionApply.getClinicId()).getDeptId());
            prescriptionApply.setApplyOn(NumberUtils.getClinicPrescription(prescriptionApply.getClinicId()));//处方号
        } else {  // 住院
            prescriptionApply.setBillingDept((UserUtils.getUser()!=null&&UserUtils.getUser().getOrgDept()!=null)?UserUtils.getUser().getOrgDept().getId():"");
            prescriptionApply.setApplyOn(NumberUtils.getVisitPrescription(prescriptionApply.getVisitId()));
        }
//		prescriptionApply.setApplyOn("1");
        prescriptionApply.setConfirmFlag(Global.NO);
        prescriptionApply.setChargeFlag(BaseEntity.CHARGE_OF_NO);
        prescriptionApply.setPrescStatus(Global.NO);//未保存到orders
        int i = prescriptionApplyService.save(prescriptionApply);
        if (i > 0) {
            data.setCode("info");
        } else {
            data.setCode("error");
            data.setData("保存门诊处方主表失败");
        }
        return data;
    }

    @RequiresPermissions("user")
    @RequestMapping(value = "delete")
    @ResponseBody
    public StringData delete(PrescriptionApply prescriptionApply) {
        StringData data = new StringData();
        int i = prescriptionApplyService.remove(prescriptionApply);
        if (i > 0) {
            data.setCode("success");
            data.setData("删除处方成功");
        } else {
            data.setCode("error");
            data.setData("删除处方失败");
        }
        return data;
    }


    /**
     * @param prescriptionApply 传递参数
     * @return StringData    返回类型
     * @throws
     * @Title: drugBack
     * @Desciption: (门诊处方退药)
     * @author CTQ
     * @date 2017-03-13
     */
    @RequiresPermissions("user")
    @RequestMapping(value = "drugBack")
    @ResponseBody
    public StringData drugBack(PrescriptionApply prescriptionApply) {
        StringData data = new StringData();
        int i = prescriptionApplyService.drugBack(prescriptionApply);
        if (i > 0) {
            data.setCode("success");
            data.setData("门诊处方退药成功");
        } else {
            data.setCode("error");
            data.setData("门诊处方退药失败");
        }
        return data;
    }

    /**
     * @param prescriptionApply 传递参数
     * @return String    返回类型
     * @throws
     * @Title: applyIndex
     * @Desciption: (加载待发药处方主表列表)
     * @author zhuq
     * @date 2017-03-21
     */
    @RequiresPermissions("user")
    @RequestMapping(value = {"findByClinic", ""})
    public String findByClinic(PrescriptionApply prescriptionApply, HttpServletRequest request, HttpServletResponse response, Model model) {
        prescriptionApply.setInoroutFlag("0"); //门诊
        prescriptionApply.setChargeFlag("1");  //已付款
        prescriptionApply.setConfirmFlag("0");  //未发药
        Page<PrescriptionApply> page = prescriptionApplyService.findByClinicPage(new Page<PrescriptionApply>(request, response), prescriptionApply);
        model.addAttribute("page", page);
        return "modules/drugOut/clinicPrescOutIndex";
    }

    /**
     * @param prescriptionApply 传递参数
     * @return String    返回类型
     * @throws
     * @Title: applyIndex
     * @Desciption: (加载已发药处方主表列表)
     * @author zhuq
     * @date 2017-03-21
     */
    @RequiresPermissions("user")
    @RequestMapping(value = {"drugOutRecordClinic", ""})
    public String findDrugOutClinic(PrescriptionApply prescriptionApply, HttpServletRequest request, HttpServletResponse response, Model model) {
        prescriptionApply.setInoroutFlag("0"); //门诊
        Page<PrescriptionApply> page = prescriptionApplyService.findDrugOutClinicPage(new Page<PrescriptionApply>(request, response), prescriptionApply);
        model.addAttribute("page", page);
        return "modules/drugOut/drugOutRecordClinicIndex";
    }

    /**
     * @param prescriptionApply 传递参数
     * @return String    返回类型
     * @throws
     * @Title: applyIndex
     * @Desciption: (加载已发药处方主表列表)
     * @author zhuq
     * @date 2017-03-21
     */
    @RequiresPermissions("user")
    @RequestMapping(value = {"drugInpRecordClinic", ""})
    public String findDrugInpClinic(PrescriptionApply prescriptionApply, HttpServletRequest request, HttpServletResponse response, Model model) {
        prescriptionApply.setInoroutFlag("1"); //住院
        Page<PrescriptionApply> page = prescriptionApplyService.findDrugOutInpPage(new Page<PrescriptionApply>(request, response), prescriptionApply);
        model.addAttribute("page", page);
        return "modules/drugOut/drugInpRecordClinicIndex";
    }

    @RequiresPermissions("user")
    @RequestMapping(value = {"findByInp", ""})
    public String findByInp(PrescriptionApply prescriptionApply, HttpServletRequest request, HttpServletResponse response, Model model) {
        prescriptionApply.setInoroutFlag("1"); //住院处方
        prescriptionApply.setChargeFlag("0");  //未付款
        prescriptionApply.setConfirmFlag("0");  //未发药
        Page<PrescriptionApply> page = prescriptionApplyService.findByInpPage(new Page<PrescriptionApply>(request, response), prescriptionApply);
        model.addAttribute("page", page);
        return "modules/drugOut/inpPrescOutIndex";
    }

    @RequiresPermissions("user")
    @RequestMapping(value = {"findByOperat", ""})
    public String findByOperat(PrescriptionApply prescriptionApply, HttpServletRequest request, HttpServletResponse response, Model model) {
        prescriptionApply.setInoroutFlag("3"); //住院手术
        prescriptionApply.setChargeFlag("0");  //未付款
        prescriptionApply.setConfirmFlag("0");  //未发药
        Page<PrescriptionApply> page = prescriptionApplyService.findByClinicPage(new Page<PrescriptionApply>(request, response), prescriptionApply);
        model.addAttribute("page", page);
        return "modules/drugOut/operationPrescOutIndex";
    }

    /**
     * @param prescriptionApply 传递参数
     * @Title: applyIndex
     * @Desciption: (加载手术未发药主表：处方主表)
     * @author zhuq
     * @date 2017-03-21
     */
    @RequiresPermissions("user")
    @RequestMapping(value = {"findByOperation"})
    public String findByOperation(PrescriptionApply prescriptionApply,HttpServletRequest request, HttpServletResponse response, Model model) {
        prescriptionApply.setInoroutFlag("3"); //住院手术
        prescriptionApply.setChargeFlag("0");  //未付款
        prescriptionApply.setConfirmFlag("0");  //未发药
        OperationCost operationCost=new OperationCost();
        operationCost.setPerformDept(null != UserUtils.getUser().getOrgDept() ? UserUtils.getUser().getOrgDept().getId() : "");
        operationCost.updateOrgId();
        operationCost.setPrescFlag("0");
        operationCost.setStorageId(prescriptionApply.getImplementDept());
        operationCost.setItemClass("A");
        operationCost.setInoroutFlag("1");
        List<OperationCost>operationCostList=operationCostService.findByPrescFlag(operationCost);
        Page<PrescriptionApply> page = prescriptionApplyService.findByOperationPage(new Page<PrescriptionApply>(request, response), prescriptionApply);
        model.addAttribute("page", page);
        model.addAttribute("operationCostList",operationCostList);
        return "modules/operation/generatePrescriptionIndex";
    }

    /**
     * @param prescriptionApply 传递参数
     * @return StringData    返回类型
     * @Desciption: 门诊处方发药
     * @author ZhuQ
     * @date 2017-03-21
     */
    @RequiresPermissions("user")
    @RequestMapping(value = "clinicDrugOut")
    @ResponseBody
    public StringData clinicDrugOut(PrescriptionApply prescriptionApply) {
        StringData data = new StringData();
        String i = prescriptionApplyService.clinicDrugOut(prescriptionApply);
        if ("1".equals(i)) {
            data.setCode("success");
            data.setData("门诊处方发药成功");
        } else if ("0".equals(i)) {
            data.setCode("error");
            data.setData("门诊处方发药失败");
        } else {
            data.setCode("quantity");
            data.setData(i + "库存量不足");
        }
        return data;
    }

    /**
     * @param prescriptionApply 传递参数
     * @return StringData    返回类型
     * @Desciption: 门诊处方退药
     * @author ZhuQ
     * @date 2017-03-21
     */
    @RequiresPermissions("user")
    @RequestMapping(value = "clinicDrugIn")
    @ResponseBody
    public StringData clinicDrugIn(PrescriptionApply prescriptionApply) {
        StringData data = new StringData();
        String i = prescriptionApplyService.clinicDrugIn(prescriptionApply);
        if ("1".equals(i)) {
            data.setCode("success");
            data.setData("门诊处方发药成功");
        } else if ("0".equals(i)) {
            data.setCode("error");
            data.setData("门诊处方发药失败");
        } else {
            data.setCode("error");
            data.setData(i + "库存量不足");
        }
        return data;
    }

    /**
     * @param prescriptionApply 传递参数
     * @return StringData    返回类型
     * @Desciption: 住院处方退药
     * @author ZhuQ
     * @date 2017-03-21
     */
    @RequiresPermissions("user")
    @RequestMapping(value = "inpDrugIn")
    @ResponseBody
    public StringData inpDrugIn(PrescriptionApply prescriptionApply) {
        StringData data = new StringData();
        String i = prescriptionApplyService.inpDrugIn(prescriptionApply);
        if ("1".equals(i)) {
            data.setCode("success");
            data.setData("住院处方退药成功");
        } else if ("0".equals(i)) {
            data.setCode("error");
            data.setData("住院处方退药失败");
        }
        return data;
    }

    /**
     * @param prescriptionApply 传递参数
     * @return StringData    返回类型
     * @Desciption: 住院处方发药
     * @author ZhuQ
     * @date 2017-03-21
     */
    @RequiresPermissions("user")
    @RequestMapping(value = "inpDrugOut")
    @ResponseBody
    public StringData inpDrugOut(PrescriptionApply prescriptionApply) {
        StringData data = new StringData();
        String i = prescriptionApplyService.inpDrugOut(prescriptionApply);
        if ("1".equals(i)) {
            data.setCode("success");
            data.setData("住院处方发药成功");
        } else if ("0".equals(i)) {
            data.setCode("error");
            data.setData("住院处方发药失败");
        } else {
            data.setCode("error");
            data.setData(i + "库存量不足");
        }
        return data;
    }

    /**
     * 住院处方列表
     *
     * @param prescriptionApply
     * @param request
     * @param response
     * @param model
     * @return
     */
    @RequiresPermissions("user")
    @RequestMapping(value = {"prescriptionVisit", ""})
    public String prescriptionVisit(PrescriptionApply prescriptionApply, HttpServletRequest request, HttpServletResponse response, Model model) {
        //住院处方状态为1
        String pageDay = prescriptionApply.getDay();
        if (pageDay != null && pageDay != "") {
            int day = Integer.parseInt(prescriptionApply.getDay());
            Date date = new Date();
            Calendar calendar = Calendar.getInstance();  //得到日历
            calendar.setTime(date);//把当前时间赋给日历
            calendar.add(Calendar.DAY_OF_MONTH, -day);  //设置为前?天
            Date dBefore = calendar.getTime();   //得到前?天的时间
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
            String startTime = df.format(dBefore);
            String endTime = df.format(date);
            prescriptionApply.setStartTime(startTime);
            prescriptionApply.setEndTime(endTime);
        }
        Page<BaseDto> page = prescriptionApplyService.findApplyPage(new Page<BaseDto>(request, response), prescriptionApply);
        model.addAttribute("page", page);
        return "modules/nurse/prescriptionInfo";
    }

    /**
     * 处方汇总打印
     * @param prescriptionApply
     * @return
     * @author CTQ
     */
    @RequiresPermissions("user")
    @RequestMapping(value = {"printPrescNurses", ""})
    @ResponseBody
    public StringData printPrescNurses(PrescriptionApply prescriptionApply){
        StringData stringData =new StringData();
        String pageDay = prescriptionApply.getDay();
        if (StringUtils.isNotBlank(pageDay)) {
            int day = Integer.parseInt(prescriptionApply.getDay());
            Date date = new Date();
            Calendar calendar = Calendar.getInstance();  //得到日历
            calendar.setTime(date);//把当前时间赋给日历
            calendar.add(Calendar.DAY_OF_MONTH, -day);  //设置为前?天
            Date dBefore = calendar.getTime();   //得到前?天的时间
            String startTime = DateUtils.formatDate(dBefore,"yyyy-MM-dd HH:mm:ss");
            String endTime = DateUtils.formatDate(date,"yyyy-MM-dd HH:mm:ss");
            prescriptionApply.setStartTime(startTime);
            prescriptionApply.setEndTime(endTime);
        }
        String printPath = prescriptionApplyService.printPrescNurses(prescriptionApply);
        stringData.setData(printPath);
        stringData.setCode("success");
        return stringData;
    }



    @RequiresPermissions("user")
    @RequestMapping(value = "selectHistory")
    public String selectHistory(String patientId,Model model){
        List<PrescriptionApply> list = prescriptionApplyService.selectHistory(patientId);
        model.addAttribute("list",list);
//        List<PrescriptionItem> prescriptionItemList = prescriptionItemService.selectHistory()
        return "modules/doctor/prescription/selectHistory/prescSelectHistoryIndex";
    }

    @RequiresPermissions("user")
    @RequestMapping(value = "printPresc")
    @ResponseBody
    public StringData printPresc(String applyId,String applyOn,String clinicId,String visitId,String patientId){
        StringData stringData = new StringData();
        String printPath = prescriptionApplyService.printPresc(applyId, applyOn,clinicId,patientId,visitId);
        stringData.setData(printPath);
        stringData.setCode("success");
        return stringData;
    }

    /**
     * 刷卡发药
     * @param prescriptionApply
     * @param request
     * @param response
     * @param model
     * @return
     */
    @RequiresPermissions("user")
    @RequestMapping(value = {"waitFeeDrug", ""})
    public String waitFeeDrug(PrescriptionApply prescriptionApply, HttpServletRequest request, HttpServletResponse response, Model model) {
        prescriptionApply.setInoroutFlag("0"); //门诊
        prescriptionApply.setChargeFlag("0");
        Page<PrescriptionApply> page = prescriptionApplyService.findByClinicPage(new Page<PrescriptionApply>(request, response), prescriptionApply);
        model.addAttribute("page", page);
        return "modules/drugOut/waitFeeDrug";
    }
    @RequiresPermissions("user")
    @RequestMapping(value = "buildTemplate")
    @ResponseBody
    public StringData buildTemplate(String applyId) {
        StringData stringData = new StringData();
        int num = prescriptionApplyService.buildTemplate(applyId);
        if(num>0){
            stringData.setData("生成成功");
            stringData.setCode("success");
        } else {
            stringData.setData("生成失败");
            stringData.setCode("error");
        }

        return stringData;
    }

    @RequiresPermissions("user")
    @RequestMapping(value = "retAmount")
    @ResponseBody
    public StringData retAmount(PrescriptionApply prescriptionApply) {
        StringData stringData = new StringData();
        int num = prescriptionApplyService.retAmount(prescriptionApply);
        if(num>0){
            stringData.setData("申请成功");
            stringData.setCode("success");
        } else {
            stringData.setData("申请失败");
            stringData.setCode("error");
        }
        return stringData;
    }


}